var lw;

var BBox;
var tBox;

var polygons;
var datastream =new Array();


var curX;
var curY;
var scale = 500;

var neig = 20;

var mousetypeofclick = 1;

function readdata()
{
query = "sss.txt";
	
	$.ajax({
		  type: 'POST',
		  url: query,
		  beforeSend:function(){
			  $('#info').html('<p align="center"><img src="loading.gif" width="50" height="50"/></p><br><p align="center">loading ...</p>'); 
		  },
		  success:function(data){
		  	splitdata(data);
		  	mbr(polygons);
		  	redraw();
		  },
		  error:function(){}
		  });
}

function init()
{
	canvas.addEventListener('mousemove', ev_mousemove, false);
	canvas.addEventListener('click', ev_mouseclick, false);
	
	readdata();
}
function splitdata(data)
{ 
	polygons = data.split("AREA:");
}
function mbr(dataset)
{
	var alllinesx = new Array();
	var alllinesy = new Array();
	var p = 0;
for (var i = 1; i < dataset.length; i++)
{
	var pol = dataset[i].split("POLYGON:");
	var linelist = pol[1].split(",");
	
	
	
	for (var j=0;  j<linelist.length-1; j=j+2)
	{
		alllinesx[p] = parseFloat(linelist[j]);
		alllinesy[p] = parseFloat(linelist[j+1]);
		p++;
	}
}

BBox = {Xmin: Math.min.apply(null, alllinesx), Xmax: Math.max.apply(null, alllinesx), Ymin: Math.min.apply(null, alllinesy), Ymax: Math.max.apply(null, alllinesy)};

tBox = BBox;

}

function redraw()
{
	var k = 0;
	
	datastream[k] ="@";
	k++;
	
for (var i = 1; i < polygons.length; i++)
	{
	var pol = polygons[i].split("POLYGON:");
	var linelist = pol[1].split(",");
	
	for (var j = 0; j<linelist.length; j++)
		{
			datastream[k] = linelist[j];
			k++;
		}
		datastream[k] ="@";
		k++;
	}
	datastream.pop();
	
	var newdata = transform(datastream, tBox, canvas.width, canvas.height);	
	draw(newdata, BBox, false);
}

function draw(newdata, Boxobj, fill, fillcolor)
{	
	var canvas = document.getElementById("canvas");
		
	if (canvas.getContext)
	{
		var lines = canvas.getContext("2d");
		lines.beginPath();
		
		for (var i=0; i < newdata.length; i=i)
		{
			if(newdata[i] == "@"){
			lines.moveTo(newdata[i+1],newdata[i+2]); i++;}
			else
			{
			lines.lineTo(newdata[i],newdata[i+1]);
			i=i+2;
			}

        	}
        	
        	if(fill == true)
        	{
        	lines.fillStyle   = '#'+fillcolor;
        	lines.fill();
        	}
        	lines.strokeStyle = "#000000";
        	lines.stroke();
        	lines.closePath();
	}
}
function transform(data, Boxobj, width , height)
{
	var newdata = new Array();
	
	lw = Boxobj.Xmax-Boxobj.Xmin;
	
	for (var i =0; i < data.length; i=i)
	{
		if (data[i] == "@"){newdata[i] ="@"; i++;}
		else
		{
		newdata[i] = parseFloat(((data[i]-Boxobj.Xmin)/lw)*width);
		newdata[i+1] = parseFloat(height-((data[i+1]-Boxobj.Ymin)/lw)*width);
		i=i+2;
		}
	}
	return newdata;
}
function ev_mousemove (ev)
{
	var canvas = document.getElementById("canvas");
	
	var pixel = getpixelsize(canvas.width);
	
	if ($.browser.mozilla)
	{
	var xt = tBox.Xmin+(ev.layerX)*pixel;
	var yt = tBox.Ymin+(canvas.height - ev.layerY)*pixel;	
	}
	else
	{
	var xt = tBox.Xmin+(ev.offsetX)*pixel;
	var yt = tBox.Ymin+(canvas.height - ev.offsetY)*pixel;
	}
	
	var x = Math.round(xt*100)/100;
	var y = Math.round(yt*100)/100;
	
	curX= x;
	curY= y;
	
	$('#info').html("pixel size: " +pixel+" X: "+x+" Y:"+y);
}
function getpixelsize(width)
{
	lw = tBox.Xmax - tBox.Xmin;
	
	var pixel = Math.round((lw/width)*100)/100;
	
	return pixel;
}
function setmouseclick(type)
{
	mousetypeofclick = type;
}
function ev_mouseclick (ev)
{
	var canvas = document.getElementById("canvas");
	if (mousetypeofclick ==0)
	{
	canvas.height = canvas.height;
	
	var pixel = getpixelsize(canvas.width);	
	
	var a = curX -(0.8 * canvas.width * pixel);
	var b = curX +(0.8 * canvas.width * pixel);
	var c = curY -(0.8 * canvas.height * pixel);
	var d = curY +(0.8 * canvas.height * pixel);
	
	scale = scale/1.2;
	
	tBox.Xmax = b;
	tBox.Xmin = a;
	tBox.Ymin = c;
	tBox.Ymax = d;
	
	var newdata = transform(datastream, tBox, canvas.width, canvas.height);	
	draw(newdata, tBox, false);
	}
	if (mousetypeofclick ==1)
	{
	canvas.height = canvas.height;
	
	var pixel = getpixelsize(canvas.width);	
	
	var a = curX -(0.8 * (canvas.width * pixel)/2);
	var b = curX +(0.8 * (canvas.width * pixel)/2);
	var c = curY -(0.8 * (canvas.width * pixel)/2);
	var d = curY +(0.8 * (canvas.width * pixel)/2);
	
	scale = scale/1.2;
	
	tBox.Xmax = b;
	tBox.Xmin = a;
	tBox.Ymin = c;
	tBox.Ymax = d;
	
	var newdata = transform(datastream, tBox, canvas.width, canvas.height);	
	draw(newdata, tBox, false);
	}
	if (mousetypeofclick ==2)
	{
		var clickp = new Array();
		clickp[0]= curX;
		clickp[1]= curY;
		
		var newpoint = transform(clickp, tBox, canvas.width, canvas.height)
		isPointInPoly(newpoint[0], newpoint[1]);	
	}
}
function isPointInPoly(x, y)
{
	var mpoly = getnearest(neig);
	var spoly = mpoly.split("@");
	
	for (var b = 0; b < spoly.length; b++)
	{
		var poly = new Array();
		var polyr = new Array();
		var tpoly = spoly[b].split(",");
		
		var newdata = transform(tpoly, tBox, canvas.width, canvas.height);
		
		for (var k =0; k < tpoly.length; k=k+2)
		{
			polyr[k/2] ={x: parseFloat(newdata[k]), y: parseFloat(newdata[k+1])};
		}
		
		var poly = Simplify(polyr, 2);
		
		var t = 0;
		
	for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i)
		((poly[i].y <= y && y < poly[j].y) || (poly[j].y <= y && y < poly[i].y))
		&& (x < (poly[j].x - poly[i].x) * (y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x)
		&& (c = !c);

		
		if (c == true)
		{
				
			draw(newdata, tBox, true, "00f"); 
		}
	}
}
function getnearest(no)
{
	var spatialindex = new Array();
	var j = 0;
	for (var i = 0; i < datastream.length; i++)
	{
		if (datastream[i] == "@")
		{
			var t = Math.sqrt(Math.pow(datastream[i+1]-curX,2)+Math.pow(datastream[i+2]-curY,2));
			spatialindex[j] = {index: j,dist: t};
			j++;
		}
	}
	spatialindex.sort(sortMultiDimensional)
	
	var pol_count = -1;
	var mpoly ="";
	var final_pol_count =0;
	
	var tempindex = new Array();
	for(var k = 0; k <no; k++)
	{
		tempindex[k] = spatialindex[k].index;
	}
	
	tempindex.sort(sortNumber);
	
	var test =new Array();
	test[0] ="@";
	var testin = 1;
	
	for (var i = 0; i < datastream.length; i++)
	{
		if (datastream[i] == "@")
		{
			pol_count++;
		}
		if (tempindex[final_pol_count] == pol_count)
		{
			i++;
			while(datastream[i] != "@")
			{
				test[testin] = datastream[i];
				testin++;
				mpoly = mpoly+ datastream[i]+",";
				i++;
			}
			test[testin] ="@";
			
			//draw(test, tBox,true, "f0f");
			
			test = [];
			test[0] ="@";
			testin = 1;
			
			i = i-2;
				
			mpoly = mpoly.slice(0,-1);
			mpoly = mpoly+"@";
		final_pol_count++;
		
		}
		if(final_pol_count ==no)
		{
			break;
		}

	}
	mpoly = mpoly.slice(0,-1);
	return mpoly;
}
function sortMultiDimensional(a,b)
{ 
    	var x = a.dist;
	var y = b.dist;
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortNumber(a,b)
{
return a - b;
}
function Simplify(polygon, tolerance)
{
	var polylines = new Array();
	polylines[0] = polygon[0];
	var ivertex = 0;
	var ipoint =0;
     for (var icontour = 0; icontour < polygon.length- 2; icontour++)
     {
		 var point1 =  new Array(); 
		 point1 = {
		 	x: polygon[ivertex].x,
		 	y: polygon[ivertex].y
		 };
		 
		 var point2 =  new Array(); 
		 point2 = {
		 	x: polygon[icontour + 2].x,
		 	y: polygon[icontour + 2].y
		 };

                                
	 	 var MidPoints = new Array();

         for (var j = 0; j < (icontour + 1 - ivertex); j++)
         {
         	MidPoints[j] = polygon[ivertex + j + 1];
         }

            var D = Math.sqrt(Math.pow((point1.x - point2.x), 2) + Math.pow((point1.y - point2.y), 2));
            var y1my2 = (point1.y - point2.y);
            var x2mx1 = (point2.x - point1.x);
            var C = (point2.y * point1.x) - (point1.y * point2.x);
			
			var run = 1;

            for (var i = 0; i < MidPoints.length; i++)
            {
                var dist = Math.abs(MidPoints[i].x * y1my2 + MidPoints[i].y * x2mx1 + C) / D;
                if (dist >   tolerance)
                {
                    run = -1;
                }
            }

                                if (run == -1)
                                {
                                    ipoint++;
                                    ivertex = icontour + 1;
                                    polylines[ipoint] = polygon[icontour + 1];
                                }
		}
		polylines[ipoint+1] = polygon[polygon.length-2];	
		polylines[ipoint+2] = polygon[polygon.length-1];		
		
		return polylines;						
}